package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.commmon.R;
import org.example.mapper.VipMapper;
import org.example.pojo.Vip;
import org.example.service.VipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;


@Service
public class VipServiceImpl extends ServiceImpl<VipMapper, Vip> implements VipService {
    @Autowired
    private VipMapper vipMapper;


    @Override
    public R<Vip> getEmployee(HttpServletRequest request, Vip vip) {

        //登陆的用户非空
        String username = vip.getUsername();
        //查询数据库是否有这个用户
        Vip e = vipMapper.selectByUserName(username);
        if (e==null) return R.error("用户名不存在");
        //查到后比对密码
        String MD5Pwd = DigestUtils.md5DigestAsHex(vip.getPassword().getBytes());
        //如果密码不匹配
        if (!MD5Pwd.equals(e.getPassword())) return R.error("密码错误");
        //密码匹配后再去匹配账号状态
        Integer status = e.getStatus();
        if (status==0) return R.error("登陆失败：账号已禁用");
        //账号密码状态都正常后登陆成功 设置session
        request.getSession().setAttribute("vip",e.getId());
        return R.success(e);
    }

    @Override
    public Page getPage(int page, int pageSize, String name) {
        //分页构造器  某一页
        Page page1=new Page(page, pageSize);
        /**
         * 如果后需要用到条件分页
         * 就增加一个条件构造器
         */
        //条件构造器
        LambdaQueryWrapper<Vip> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        //传入条件 name
        /**
         * 判断查询条件是否null
         * null时不执行
         */
        if (name!=null)  lambdaQueryWrapper.like(Vip::getName,name);
        //添加排序
        lambdaQueryWrapper.orderByDesc(Vip::getUpdateTime);

        //执行查询
        page(page1,lambdaQueryWrapper);
        return page1;
    }
}
